package com.ssy.lingxi.message.websocket.cluster;

import com.ssy.lingxi.component.rabbitMQ.constants.MessageConstants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * rabbitMQ配置
 * @author yzc
 * @version 2.0.0
 * @date 2021/2/8
 */
@Configuration
public class WsMQConfig {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Value("${spring.cloud.client.ip-address}_${server.port}")
    private String queueId;

    /*********************************** 会员消息 *****************************************/

    @Bean
    Queue member_message_queue() {
        return new Queue(getQueueName(), false);
    }

    @Bean
    FanoutExchange member_message_exchange() {
        return new FanoutExchange(MessageConstants.ws_deliver_message_exchange);
    }

    @Bean
    Binding member_message_binding() {
        return BindingBuilder.bind(member_message_queue()).to(member_message_exchange());
    }

    /**
     * 设置消息处理
     * @param wsMessageListener
     * @return
     */
    @Bean
    public SimpleMessageListenerContainer mqMessageContainer(WsMessageListener wsMessageListener) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(rabbitTemplate.getConnectionFactory());
        container.setQueueNames(getQueueName());
        container.setExposeListenerChannel(true);
        // 消息处理类
        container.setMessageListener(wsMessageListener);
        return container;
    }

    private String getQueueName(){
        return MessageConstants.ws_deliver_message_queue + "_" + queueId;
    }
}
